package controller.fileUploadDownload;

import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import properties.SystemProperty;
import util.io.FtpUtil;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;

/**
 * Created by Administrator on 2017/12/18.
 */
@Controller
public class KindeditorUploadController {
    static HashMap<String, String> extMap = new HashMap<String, String>();
    static {
        //定义允许上传的文件扩展名
        extMap.put("image", "gif,GIF,jpg,JPG,jpeg,JPEG,png,PNG,bmp,BMP");
        extMap.put("flash", "swf,flv");
        extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
        extMap.put("file", "doc,docx,xls,xlsx,ppt,pptx,htm,html,txt,zip,rar,gz,bz2,pdf,sql,exe,jar,pdm,chm,jnt");
    }

    @RequestMapping("kindeditor/upload")
    @ResponseBody
    public JSONObject upload(@RequestParam(value = "dir", defaultValue = "image") String dirName,
                             @RequestParam("imgFile") MultipartFile file) throws Exception {

        if (!extMap.containsKey(dirName)) {
            return getError("目录名不正确。");
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String ymd = sdf.format(new Date());
        String savePath = SystemProperty.getNoticeFileFolder() + "/" + ymd + "/" + dirName + "/";


        //检查扩展名
        String fileName=file.getOriginalFilename();
        String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        if (!Arrays.asList(extMap.get(dirName).split(",")).contains(fileExt)) {
            return getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。");
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String newFileName =fileName.substring(0,fileName.lastIndexOf("."))+'_'+ df.format(new Date()) + "_" + new Random().nextInt(100) + "." + fileExt;

        boolean result = FtpUtil.saveFileByRelativePath(file.getInputStream(), savePath, newFileName);

        if (result == false) {
            return getError("存储失败");
        } else {
            return getSuccess("downloadFileByPath?pathName=" + savePath + newFileName,fileName);
        }
    }


    private JSONObject getError(String message) {
        JSONObject obj = new JSONObject();
        obj.put("error", 1);
        obj.put("message", message);
        return obj;
    }

    private JSONObject getSuccess(String url,String fileName) {
        JSONObject obj = new JSONObject();
        obj.put("error", 0);
        obj.put("url", url);
        obj.put("fileName",fileName);
        return obj;
    }


}
